package com.slife.serial.service;

import cn.hutool.core.util.HexUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.slife.serial.domain.TbEltic;
import com.slife.serial.service.TbElticService;
import com.slife.serial.utils.ElecticUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Date;


@Component
public class SerialPortHandler {
    private static final int DEFAULT_BAUD_RATE = 9600;

    private  SerialPort serialPort;
    private static final int DEFAULT_DATA_BITS = 8;
    @Value("${server.serial}")
    private String portName;


    @Autowired
    private TbElticService elticService;

    private String index = "";


    /*
    @PostConstruct
    public void init(){


        serialPort = SerialPort.getCommPort(portName);

        System.out.println("初始化 SerialPort 开始");
        if (serialPort.openPort()) {
            //打开串口成功，设置端口参数
            serialPort.setBaudRate(DEFAULT_BAUD_RATE);
            serialPort.setNumDataBits(DEFAULT_DATA_BITS);
            serialPort.setNumStopBits(1);
            serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
            serialPort.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 2000, 2000);

            System.out.println("添加监听对象 ---");
//实时量浮点数读取
//080400630002814C
//正向流量累积读取
//0804006B0004808C
            serialPort.addDataListener(new SerialPortDataListener() {
                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
                }

                @Override
                public void serialEvent(SerialPortEvent serialPortEvent) {
                    if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
                        return;
                    }
                    byte[] newData = new byte[serialPort.bytesAvailable()];
                    int numRead = serialPort.readBytes(newData, newData.length);
                    char[] chars = HexUtil.encodeHex(newData);
                    String message =String.copyValueOf(chars);
                    String value = ElecticUtils.parseToValue(message);

                    TbEltic eltic = new TbEltic();
                    if (message.startsWith("08")){
                        eltic.setName("出水口");
                    }else{
                        eltic.setName("进水口");
                    }

//                    eltic.setTitle("瞬时流量");
                    eltic.setValue(Float.valueOf(value));
                    eltic.setTitle(index);
                    eltic.setMessage(message);
                    eltic.setFlag(0);
                    eltic.setCreateTime(new Date());
                    elticService.save(eltic);

                    System.out.println("message = " +message + "  === " +value);
                }
            });
        }

    }

   */
    public void sendMessage(String msg){
        System.out.println("发送消息" + msg);
        index = msg;
        byte[] bytes = HexUtil.decodeHex(msg);
        serialPort.writeBytes(bytes,bytes.length);

    }
    @PreDestroy
    public void destory(){
        System.out.println("销毁监听对象：SerialPort ");
        if (serialPort != null && serialPort.isOpen()) {
            serialPort.closePort();
        }
    }


}
